package com.huaixia18.systemnotice.service;

import com.huaixia18.systemnotice.domain.PrivateMessage;
import com.huaixia18.systemnotice.domain.PrivateChat;
import com.huaixia18.systemnotice.mapper.PrivateChatMapper;
import com.huaixia18.systemnotice.mapper.PrivateMessageMapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class PrivateChatService {

    @Autowired
    private PrivateChatMapper privateChatMapper;
    @Autowired
    private PrivateMessageMapper privateMessageMapper;

    /**
     * 创建或获取聊天室
     * @param user1Id
     * @param user2Id
     * @return 聊天室对象
     */
    public PrivateChat getOrCreatePrivateChat(Long user1Id, Long user2Id) {
        PrivateChat chat = privateChatMapper.findByUser1IdAndUser2Id(user1Id, user2Id);
        if (chat == null) {
            chat = privateChatMapper.findByUser2IdAndUser1Id(user2Id, user1Id);
            if (chat == null) {
                chat = new PrivateChat();
                chat.setUser1Id(user1Id);
                chat.setUser2Id(user2Id);
                chat.setLastMessage("");
                privateChatMapper.insert(chat);
            }
        }
        return chat;
    }

    /**
     * 发送私信
     * @param message 私信对象
     */
    public void sendPrivateMessage(PrivateMessage message) {
        privateMessageMapper.insert(message);
        PrivateChat chat = getOrCreatePrivateChat(message.getSenderId(), message.getRecipientId());
        chat.setLastMessage(message.getContent());
        privateChatMapper.insert(chat);
    }

    /**
     * 获取用户的私信列表
     * @param recipientId 用户ID
     * @return 私信列表
     */
    public List<PrivateMessage> getPrivateMessages(Long recipientId) {
        return privateMessageMapper.findByRecipientIdAndState(recipientId, false);

    }
}
